//
//  BMListViewController.m
//  bum
//
//  Created by xingshuai on 2020/12/29.
//

#import "BMListViewController.h"

#import "BMListTableViewCell.h"
#import "BMViewController.h"

@interface BMListViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) NSMutableArray *photoList;

@end

@implementation BMListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self creatViewUI];
    //[self reloadListArray];
    [self loadAllPhotoData];
    
}

-(NSMutableArray *)photoList {
    if (!_photoList) {
        _photoList = [[NSMutableArray alloc]init];
    }
    return _photoList;
}

#pragma mark - 获取相册内所有照片资源
- (void)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending {
    [self.photoList removeAllObjects];
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *asset = (PHAsset *)obj;

        if ([obj isKindOfClass:[PHAsset class]]) {
             [self.photoList addObject:asset];
        }
    }];

    PHCachingImageManager *cachingImage = [[PHCachingImageManager alloc] init];
    [cachingImage startCachingImagesForAssets:self.photoList targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:nil];
}

-(void)creatViewUI {
    CGFloat h_wid = ScreenHeight > 736 ? 88 : 64;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(h_wid);
    }];
}

-(UITableView *)table {
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
    }
    return _table;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.photoList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cellId";
    BMListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[BMListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    if (self.photoList.count > indexPath.row) {
        cell.albumModel = [self.photoList objectAtIndex:indexPath.row];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BMAlbumModel *model = [self.photoList objectAtIndex:indexPath.row];
    BMViewController *vc = [[BMViewController alloc]init];
    vc.assetsList = model.assets;
    [self.navigationController pushViewController:vc animated:YES];
}


//获取图像数据
-(void)loadAllPhotoData{
    [self.photoList removeAllObjects];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        // 获得全部相片
        PHFetchResult<PHAssetCollection *> *cameraRolls = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
        
        // 我的照片流
        PHFetchResult *myPhotoStreamAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumMyPhotoStream options:nil];
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
        PHFetchResult *syncedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumSyncedAlbum options:nil];
        PHFetchResult *sharedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumCloudShared options:nil];
        
        
        for (PHAssetCollection *collection in cameraRolls) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        
        for (PHAssetCollection *collection in myPhotoStreamAlbum) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        for (PHAssetCollection *collection in smartAlbums) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        
        for (PHAssetCollection *collection in topLevelUserCollections) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        for (PHAssetCollection *collection in syncedAlbums) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        
        for (PHAssetCollection *collection in sharedAlbums) {
            BMAlbumModel *model = [[BMAlbumModel alloc] init];
            model.collection = collection;

            if (![model.collectionNumber isEqualToString:@"0"]) {
                [weakSelf.photoList addObject:model];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.table reloadData];
        });
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
